package com.moshme.framework.config;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Kieyfr
 * @version 1.0
 * @description 数据库以","为分隔的字符串转换为List列表
 * @date 2023/5/22 16:09
 */
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes({List.class})
public class SeparatorCommaToListTypeHandler extends BaseTypeHandler<List<String>> {

    private static final String DELIM = ",";

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List<String> strings, JdbcType jdbcType) throws SQLException {
//        String value = StringUtils.collectionToDelimitedString(strings, DELIM);
        String value = "";
        if (!CollectionUtils.isEmpty(strings)){
            value = strings.stream().collect(Collectors.joining(","));
        }

        preparedStatement.setString(i, value);
    }
    @Override
    public List<String> getNullableResult(ResultSet resultSet, String s) throws SQLException {
        String value = resultSet.getString(s);
//        return Arrays.asList(StringUtils.tokenizeToStringArray(value, DELIM));
        List<String> list = new ArrayList<>();
        if (value!=null){
            list = Arrays.asList(value.split(DELIM,-1));
        }
        return list;
    }

    @Override
    public List<String> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        String value = resultSet.getString(i);
//        return Arrays.asList(StringUtils.tokenizeToStringArray(value, DELIM));
        List<String> list = new ArrayList<>();
        if (value!=null){
            list = Arrays.asList(value.split(DELIM,-1));
        }
        return list;
    }

    @Override
    public List<String> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        String value = callableStatement.getString(i);
//        return Arrays.asList(StringUtils.tokenizeToStringArray(value, DELIM));
        List<String> list = new ArrayList<>();
        if (value!=null){
            list = Arrays.asList(value.split(DELIM,-1));
        }
        return list;
    }
}
